from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Image(models.Model):
    name = models.CharField(max_length=64)


class Project(models.Model):
    name = models.CharField(max_length=128)
    introduction = models.CharField(max_length=256)
    ispublic = models.BooleanField(default=True)
    createtime = models.DateTimeField(auto_now_add=True)
    edittime = models.DateTimeField()
    stars = models.IntegerField(default=0)
    folks = models.IntegerField(default=0)
    image = models.ForeignKey(Image, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    views = models.PositiveIntegerField(default=0)


class StarsPro(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)


class Examples(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)


def ProjectSerializer_one(project):
    res = {
        "id": project.id,
        "name": project.name,
        "introduction": project.introduction,
        "createtime": project.createtime,
        "edittime": project.edittime,
        "ispublic":project.ispublic,
        "stars": project.stars,
        "folks": project.folks,
        "image":project.image.id,
        "views":project.views,
        "user":project.user.username
    }
    if hasattr(project,"isstar"):
        res["isstar"] = project.isstar
    return res


def ProjectSerializer(data):
    if type(data) == Project:
        return ProjectSerializer_one(data)
    else:
        res = []
        for d in data:
            res.append(ProjectSerializer_one(d))
        return res

